﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Module.Interfaces.Controller;
using Core.Module.Interfaces;
using Core.Module.Interfaces.Manager;
using Microsoft.Practices.Unity;
using Core.Module.Interfaces.Model;
using umbraco.BusinessLogic.Utils;

namespace Core.Module.Controller
{
    public class ModuleController:IModuleController<IFrontend>
    {
        private Dictionary<string, List<IModule>> SiteModules;
        [Dependency]
        public IModuleManager<IFrontend> Manager { get; set; }

        public ModuleController()
        {
            SiteModules = new Dictionary<string, List<IModule>>();
        }

        public List<Type> Get()
        {
            return Manager.Get();
        }

        public List<IModule> Get(ISite forSite)
        {
            if (!SiteModules.ContainsKey(forSite.Node.Id))
            {
                lock(SiteModules)
                    SiteModules.Add(forSite.Node.Id, Manager.Get(forSite));
            }
            return SiteModules[forSite.Node.Id];
        }

        public IModule Get(ISite forSite, string moduleAlias)
        {
            forSite.Modules=Get(forSite);
            if (forSite.Modules == null) return null;
            return forSite.Modules
                .Where(mi => mi.Alias.Equals(moduleAlias, StringComparison.InvariantCultureIgnoreCase))                
                .OrderBy(mi => mi.Position)
                .FirstOrDefault();
        }      

    }
}
